<template>
  <div class="user-regis-card-wrapper">
    <i class="back-to-login iconfont icon-arrow-left-bold"
    @click="$emit('toLog')"
    ></i>

		<i class="iconfont icon-cancel" @click="$emit('exit')"></i>

    <h2>找回密码</h2>

    <ul class="input-info-list">
      <li v-for="(item, idx) in infos" :key="idx">
        <component :is="(idx===1||idx===2)?'PasswordInput':'BaseInput'" 
				:placeholder="item.placeholder"
				:value="inputs[idx]"
				@change="renewInput($event.target, item.key)"
				class="info-input"/>
        <i class="iconfont icon-warning signal" v-show="ifError[idx].sign"></i>
        <p class="sig-message" v-show="ifError[idx].sign && ifError[idx].message">{{ifError[idx].message}}</p>
      </li>
    </ul>

		<div class="verification">
			<base-input
			class="veri-input"
			placeholder="请输入验证码"
			@change="renewInput($event.target, 'verification')"
			></base-input>

      <button class="send-veri" @click="sendVeri"
      :class="{sendAble: !resendCount, sendDisable: resendCount}">{{veriMsg}}</button>
		</div>

    <button class="regis-button" @click="changePwd" ref="submitBtn">更改密码</button>
  </div>
</template>

<script>
import BaseInput from '../utils/Input/BaseInput.vue';
import PasswordInput from '../utils/Input/PasswordInput.vue';

export default {
	components: {
		BaseInput,
		PasswordInput,
	},
	data() {
		return {
			inputs: {
        account: '',
        newpwd: '',
        newpwdConfirm: '',
				verification: ''
			},
			infos: [
        {
          key: 'account',
          placeholder: '请输入用户名或邮箱'
        },
				{
					key: 'newpwd',
					placeholder: '请输入新密码'
				},
				{
					key: 'newpwdConfirm',
					placeholder: '请再次输入新密码'
				}
			],
			ifError: Array.from(new Array(4), () => ({
				sign: false,
				message: ''
			})),
			ifShowPwd: false,
			ifShowPwdCon: false,
      
      resendCount: 0,
		}
	},
  computed: {
    veriMsg() {
      if(!this.resendCount) return "发送验证码";
      else return `再次发送 ${this.resendCount}s`;
    }
  },
	methods: {
    checkAccount(account) {
      if(!account.includes("@")) {
        if (account.length < 6 || account.length > 18) {
          this.ifError[0].sign = true;
          this.ifError[0].message = '用户名长度必须为6-18位';
          return true;
        } else if (/[^a-zA-Z0-9-_]/.test(account)) {
          this.ifError[0].sign = true;
          this.ifError[0].message = '用户名只能包含字母，数字，-(连字符)和_(下划线)';
          return true;
        }
      } else {
        if(!/^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+(\.([a-zA-Z]{2,4}))+$/.test(account)) {
          this.ifError[0].sign = true;
          this.ifError[0].message = '邮箱格式不正确';
          return true;
        }
      }
      this.ifError[0].sign = false;
      this.ifError[0].message = '';
    },
		checkPassword(password) {
			if(!(/[a-zA-Z]/.test(password) && /[0-9]/.test(password))) {
				this.ifError[1].sign = true;
				this.ifError[1].message = '密码至少包含一个字母和一个数字';
				return true;
			} else if(password.length < 6) {
        this.ifError[1].sign = true;
        this.ifError[1].message = '密码长度至少六位';
        return true;
      } else {
				this.ifError[1].sign = false;
				return false;
			}
		},
		checkPasswordConfirm(p1, p2) {
			if(p1 !== p2) {
				this.ifError[2].sign = this.ifError[1].sign = true;
				this.ifError[1].message = '';
				this.ifError[2].message = '两次输入密码不一致'
				return true;
			} else {
				this.ifError[2].sign = this.ifError[1].sign = false;
				return false;
			}
		},
    sendVeri() {
      if(this.resendCount) return;
      if(this.checkAccount(this.inputs.account)) {
        this.$alert({
          type: 'error',
          content: '请填写用户名或邮箱'
        });
        return;
      }
      this.$post({
        name: 'findpwd sendveri',
        url: '/findpwd/sendveri',
        data: {
          account: this.inputs.account
        },
        callback: res => {
          if(res.data.success) {
            this.$alert("请查收邮箱！")
          } else {
            this.$alert({
              type: 'error',
              content: "验证码发送失败"
            })
          }
        }
      })
      this.resendCount = 60;
      let intervalId = setInterval(() => {
        this.resendCount--;
        if(!this.resendCount) clearInterval(intervalId);
      }, 1000);
    },
		renewInput(el, key){
			this.inputs[key] = el.value;
			console.log('register card inputs: ', this.inputs);
			this.checkFormat(key)
		},
		changePwd() {
			if(this.ifError.filter(e => e.sign).length) {
				this.$alert({
          type: 'error',
          content: '请填写正确的注册信息'
        });
				return;
			}
			this.$store.commit('changePwd', {
				info: {
          newpwd: this.inputs.newpwd,
          verification: this.inputs.verification,
          account: this.inputs.account
        },
				callback: (success) => {
					success && this.$emit('exit');
				}
			});
			this.$refs.submitBtn.disabled = true;
		},
		checkFormat(key) {
			switch(key) {
				case 'newpwd':
					!this.checkPasswordConfirm(this.inputs.newpwd, this.inputs.newpwdConfirm) && this.checkPassword(this.inputs.newpwd);
					break;
				case 'newpwdConfirm':
					!this.checkPasswordConfirm(this.inputs.newpwd, this.inputs.newpwdConfirm) && this.checkPassword(this.inputs.newpwd);
					break;
        case 'account':
          this.checkAccount(this.inputs.account);
          break;
			}
		}
	},
	mounted() {
	}
}
</script>

<style scoped lang="less">
@w: var(--userFindpwdWidth);
@fs: calc(var(--userFindpwdWidth) * 0.05);
@ifs: calc(@fs * 0.8);
@iw: calc(@w * 0.7);

.user-regis-card-wrapper {
	box-sizing: border-box;
  position: relative;
	width: @w;
	padding: calc(@w * 0.1) calc((@w - @iw) / 2);
	background-color: white;
	border-radius: calc(@w * 0.02);
	text-align: center;

	.icon-cancel {
		right: 0;

		&:hover {
			transform: rotate(180deg);
		}
	}

	.back-to-login {
		left: 0;

		&:hover {
			color: var(--darkBlue);
		}
	}

	.icon-cancel,
	.back-to-login {
		--a: 3vw;
		position: absolute;
		top: 0;
		display: block;
		width: var(--a);
		height: var(--a);
		line-height: var(--a);
		text-align: center;
		font-size: 1.2vw;
		font-weight: bold;
		color: var(--black);
		transition: .5s;

		&:hover {
			cursor: pointer;
		}
	}

	h2 {
		font-size: calc(@fs * 1.5);
		color: var(--blue);
		line-height: 2;
	}

	.input-info-list {
		width: @iw;

		li {
			position: relative;
			margin-bottom: calc(@w * 0.07);
			width: @iw;
			font-size: @fs;

			.info-input {
				--baseInputWidth: @iw;
				--baseInputHeight: calc(@fs * 2);
				--baseInputFontsize: @ifs;
				--passwordInputWidth: @iw;
				--passwordInputHeight: calc(@fs * 2);
				--passwordInputFontsize: @ifs;
			}

			.signal {
				position: absolute;
				left: 105%;
				top: 0;
				text-align: center;
				font-size: calc(@fs * 1.3);
				color: var(--red);
			}

			.sig-message {
				margin-top: calc(@fs * 0.4);
				line-height: @fs;
				margin-bottom: calc(-0.7 * @fs);
				padding: 0 calc(@fs / 2);
				text-align: left;
				font-size: calc(@fs * 0.2);
				color: var(--red);
			}
		}
	}

	.verification {
		margin-bottom: @fs;
		width: @iw;
		height: calc(@fs * 2);
		display: flex;
		justify-content: space-between;
		align-items: center;

		.veri-input {
			--baseInputWidth: calc(@iw / 2);
			--baseInputHeight: calc(@fs * 2);
			--baseInputFontsize: @ifs;
		}

		.send-veri {
      width: 40%;
      height: 100%;
      text-align: center;
      border-radius: calc(@fs * 0.3);
      border: 1px solid var(--gray);
      color: var(--dark);
      font-size: @ifs;
      transition: .3s;

      &.sendDisable {
        color: var(--gray);
      }

      &:hover {
        cursor: default;
      }

      &.sendAble:hover {
        cursor: pointer;
        border-color: var(--lightBlue);
        color: var(--darkBlue);
      }
		}
	}

	.regis-button {
		width: @iw;
		line-height: 2;
		font-size: calc(@fs * 1.2);
    color: white;
    font-weight: bold;
		border-radius: 1.5vw;
		background-image: linear-gradient(-200deg, #fac0e7, #91baff);
	}

	.register-entry {
		margin: calc(@fs * 0.5) 0;
		font-size: calc(@fs * 0.5);

		span {
			color: var(--blue);

			&:hover {
				cursor: pointer;
			}
		}
	}
}
</style>